package ie.ucc.cs.anggao.finalproject.client.ui.mainpanel.infopane.PageableFlextTable;

import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Widget;

public class Pager extends Composite implements ClickListener,
		SourcesPagerEvents {

	public static final String NEXT_TOOLTIP = "Next";
	public static final String PREVIOUS_TOOLTIP = "Previous";
	public static final String PREVIOUS_IMAGE = "images/previous-arrow.gif";
	public static final String NEXT_IMAGE = "images/next-arrow.gif";

	private static final int PAGE_ARROW_SPACING = 2;
	private static final int ARROW_WIDTH = 18;

	private int currentIndex = 0;
	private Image forward;
	private Image back;
	private CanPage pageableData;
	private PagerListenerCollection pagerListeners = new PagerListenerCollection();

	public Pager(CanPage pageableData) {
		this.pageableData = pageableData;
		HorizontalPanel pagerPanel = new HorizontalPanel();
		initWidget(pagerPanel);
		pagerPanel.setSpacing(PAGE_ARROW_SPACING);
		pagerPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);

		back = new Image();
		back.setTitle(PREVIOUS_TOOLTIP);
		back.setUrl(PREVIOUS_IMAGE);
		back.setWidth(ARROW_WIDTH + "px");
		pagerPanel.add(back);
		back.addClickListener(this);
		forward = new Image();
		forward.setTitle(NEXT_TOOLTIP);
		forward.setUrl(NEXT_IMAGE);
		forward.setWidth(ARROW_WIDTH + "px");
		pagerPanel.add(forward);
		forward.addClickListener(this);
	}

	public void reset() {
		currentIndex = 0;
	}

	public void onClick(Widget sender) {
		if (sender == forward) {
			currentIndex = currentIndex + pageableData.getPageSize();
		}
		if (sender == back) {
			currentIndex = Math.max(currentIndex - pageableData.getPageSize(),
					0);
		}
		setArrowVisibility();
		pagerListeners.firePage(this, currentIndex);
	}

	public void onLoad() {
		setArrowVisibility();
	}

	private void setArrowVisibility() {
		back.setVisible(currentIndex == 0 ? false : true);
		forward
				.setVisible(pageableData.isLastPage(currentIndex) ? false
						: true);
	}

	public int getCurrentIndex() {
		return currentIndex;
	}
	
	public void setCurrentIndex(int index) {
		currentIndex = index;
	}
	
	public void addPagerListener(PagerListener listener) {
		pagerListeners.add(listener);
	}
	
	public void removePagerListener(PagerListener listener) {
		pagerListeners.remove(listener);
	}
}
